﻿using Abp.Dependency;
using Batman.Core;
using Batman.Jianbei.Forum.Core.Datas;
using Batman.Jianbei.Forum.Services.ChatRoom;
using Batman.Jianbei.Forum.Services.ChatRoom.CacheQs;
using Microsoft.EntityFrameworkCore;
using Quartz;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Jianbei.Forum.Jobs
{
    /// <summary>
    /// 聊天室成员检查
    /// </summary>
    public class RoomMemberCheckJob : ITransientDependency, IJob
    {
        public Task Execute(IJobExecutionContext context)
        {
            var roomService = IocManager.Instance.Resolve<RoomService>();
            var roomCacheService = IocManager.Instance.Resolve<RoomCacheQs>();

            using (var ctx = new ChatRoomDbFactory().CreateDbContext(null))
            {
                var adminRooms = roomCacheService.GetAdministratorsRoomIds();

                var yestertday = DateTime.Now.AddDays(-1);
                var query = ctx.RoomMask.AsNoTracking()
                                 // 排查已解散的和管理员创建的聊天室
                                 .Where(t => !t.Room.IsDismiss && !adminRooms.Contains(t.RoomId))
                                 .GroupBy(t => t.RoomId)
                                 // 最后报到时间是一天前的则是要被解散的
                                 .Where(t => t.Max(s => s.CheckIn) < yestertday)
                                 .Select(t => t.Key);

                var sql = query.ToSql();
                var unDismissRooms = query.ToList();

                if (unDismissRooms.Count == 0) return Task.CompletedTask;

                foreach (var roomId in unDismissRooms)
                {
                    roomService.Destroy(roomId);// 没人在房间-解散
                }

                return Task.CompletedTask;
            }
        }
    }
}
